<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-10-3
 * Time: 下午11:32
 */

class SearchController extends Controller {

    public function init() {
        parent::init();
        // 取得用户信息
        $user_info = $this->_session->offsetGet ( 'loginInfos' );
        $this->_view->userInfo=$user_info;
    }


    public function indexAction(){
        global $_getAreaNames,$_suppliyStateCfg,$_sphinxConfig;
        define('ITEM_PER_PAGE', 10);
        $this->_title = '现货资源';
        $this->_keywords = '现货资源';
        $this->_description = '现货资源';
        $url = "/search/index";
        //分类
        $index = new IndexModel();
        $cate = $index->getCateInfo("cate",'','');
        //获取参数
        $page=empty($_GET['page']) ? 1 :htmlspecialchars(trim($_GET['page']) , ENT_QUOTES ,'utf-8');

        $kd=empty($_GET['kd']) ? '' :htmlspecialchars(trim($_GET['kd']) , ENT_QUOTES ,'utf-8');

        $cate_name=empty($_GET['cate_name']) ? '' :htmlspecialchars(trim($_GET['cate_name']) , ENT_QUOTES ,'utf-8');

        $cates_name=empty($_GET['cates_name']) ? '' :htmlspecialchars(trim($_GET['cates_name']) , ENT_QUOTES ,'utf-8');

        $currency_name=empty($_GET['currency_name']) ? '' :htmlspecialchars(trim($_GET['currency_name']) , ENT_QUOTES ,'utf-8');

        $area_id=empty($_GET['area_id']) ? '' :htmlspecialchars(trim($_GET['area_id']) , ENT_QUOTES ,'utf-8');

        $area_name=empty($_GET['area_name']) ? '' :htmlspecialchars(trim($_GET['area_name']) , ENT_QUOTES ,'utf-8');

        $region_name=empty($_GET['region_name']) ? '' :htmlspecialchars(trim($_GET['region_name']) , ENT_QUOTES ,'utf-8');

        $brand_name=empty($_GET['brand_name']) ? '' :htmlspecialchars(trim($_GET['brand_name']) , ENT_QUOTES ,'utf-8');

        $product_name=empty($_GET['product_name']) ? '' :htmlspecialchars(trim($_GET['product_name']) , ENT_QUOTES ,'utf-8');

        $orderby=empty($_GET['order']) ? '' :htmlspecialchars(trim($_GET['order']) , ENT_QUOTES ,'utf-8');

        $minprice=empty($_GET['minprice']) ? '' :htmlspecialchars(trim($_GET['minprice']) , ENT_QUOTES ,'utf-8');

        $maxprice=empty($_GET['maxprice']) ? '' :htmlspecialchars(trim($_GET['maxprice']) , ENT_QUOTES ,'utf-8');

        $list_search=empty($_GET['list_search']) ? '' :htmlspecialchars(trim($_GET['list_search']) , ENT_QUOTES ,'utf-8');

        $delivery_area=empty($_GET['delivery_area']) ? '' :htmlspecialchars(trim($_GET['delivery_area']) , ENT_QUOTES ,'utf-8');

        $server = new SphinxClient();
        $server->SetServer($_sphinxConfig['host'],$_sphinxConfig['port']);
//        $server->SetMatchMode($_sphinxConfig['SPH_MATCH']);
        $server->SetArrayResult(true);
        $sphinx_offset = ($page-1) *ITEM_PER_PAGE;
        //搜索状态为上架的
        $server->SetFilter("status",array($_suppliyStateCfg['up']));
        $server->SetGroupBy('product_id', SPH_GROUPBY_ATTR,"");
        $server->SetLimits($sphinx_offset,ITEM_PER_PAGE,1000);
        $sphinx_info = $server->Query( $kd,"quote_src");
        //这上面的只去获取产品id product_id ，然后根据产品的id去查报价

        $condition = array();
        $conditions = array();
        $urls=array();
        if(!empty($cate_name)){
            $conditions[] = "pc.cate_name like '%{$cate_name}%'";
            $urls[]="cate_name={$cate_name}";
        }

        if(!empty($currency_name)){
            $conditions[] = "rc.name like '%{$currency_name}%'";
            $urls[]="currency_name={$currency_name}";
        }

        if(!empty($area_id)){
            $conditions[] = "iq.area_id = '{$area_id}'";
            $urls[]="area_id={$area_id}";
        }

        if(!empty($area_name)){
            $conditions[] = "r.region_name like '%{$area_name}%'";
            $urls[]="area_name={$area_name}";
        }
        $keyword_list_search=strtr($list_search, array('%'=>'\%'));
        if(!empty($list_search)){
            $conditions[] =" (p.product_name like '%{$keyword_list_search}%' or pc.cate_name like '%{$keyword_list_search}%' or pb.brand_name like '%{$keyword_list_search}%' or r.region_name like '%{$keyword_list_search}%' or iq.delivery_area like '%{$keyword_list_search}%')";
            $urls[]="list_search={$list_search}";
        }

        if(!empty($delivery_area)){
            $conditions[] = "iq.delivery_area like '%{$delivery_area}%'";
            $urls[]="delivery_area={$delivery_area}";
        }

        if(!empty($product_name)){
            $conditions[] = "p.product_name like '%{$product_name}%'";
            $urls[]="product_name={$product_name}";
        }

        if(!empty($brand_name)){
            $conditions[] = "pb.brand_name like '%{$brand_name}%'";
            $urls[]="brand_name={$brand_name}";
        }


        $having = "1=1";
        if(!empty($minprice)){
            $having .= " and min(iq.price) >= '{$minprice}'";
            $urls[]="minprice='{$minprice}'";
        }

        if(!empty($maxprice)){
            $having .= " and min(iq.price) <= '{$maxprice}'";
            $urls[]="maxprice={$maxprice}";
        }

        $url .= "?page=%d";
        $where= "1=1";
        $wheres= "1=1";
        if(empty($conditions))
        {
            $wheres  .= " AND iq.status= '{$_suppliyStateCfg['up']}'";
        } else {
            $wheres  .= " AND iq.status= '{$_suppliyStateCfg['up']}'"." AND ".implode(' AND ', $conditions);
        }
        $keyword=strtr($kd, array('%'=>'\%'));
        $search_ids = array(); //查询结果的id
        if(empty($sphinx_info['matches'])&&!empty($kd)){
            $wheres .= "  AND (p.product_name like '%{$keyword}%' or pc.cate_name like '%{$keyword}%' or pb.brand_name like '%{$keyword}%' or r.region_name like '%{$keyword}%' or iq.delivery_area like '%{$keyword}%')";
        }else{
            //这边去过滤产品的id
            if(!empty ($sphinx_info['matches']))
            {
                foreach($sphinx_info['matches'] as $row)
                {
                    $search_ids[] = $row['id'];
                }
            }
            $search_ids_str = implode(',', $search_ids);
            if(!empty($search_ids_str)){
                $condition[]    = "`iq`.`id` in ({$search_ids_str}) ";
            }else{
                $condition[]    = "`iq`.`id` in (0) ";
            }
        }

        //下面或者关系
        if(!empty($cates_name)){
            $condition[]= "pc.cate_name like '%{$cates_name}%'";
            $urls[]="cates_name={$cates_name}";
        }

        if(!empty($region_name)){
            $condition[] = "r.region_name like '%{$region_name}%'";
            $urls[]="region_name={$region_name}";
        }

        if(empty($condition))
        {
            $where  = '1=1 ';
        } else {
            $where  .= " AND ".implode(' AND ', $condition);
        }

        if(!empty($condition)){
            if(!empty($cate_name) || !empty($area_name)){
                $wheres.= " or (".$where.")";
            }else{
                $wheres.= " AND (".$where.")";
            }
        }

        if(!empty($urls)){
            $url.=  "&".implode('&',$urls);
        }

        $url.="&kd={$kd}&order={$orderby}";

        //实例化当前module
        $search = new SearchModel();
        //币种展示，这边从数据库读取，便于管理
        $CurrencyShow =  $search->getCurrencyShow("index_show='Y'");
        //这边还是要去查询地区
        $AreaShow = $search->getAreaShow("iq.status = '2' ");

        if(!empty($AreaShow)){
            foreach($AreaShow as $key=>$var){
                if(!empty($var['area_id']) && !empty($var['area_name'])){
                    $areas[] =  $var['area_id'];
                }
                unset($AreaShow[$key]);
            }
        }
        if(!empty($areas)){
            $AreaShow = array_unique($areas);
        }

        $Region =   new RegionModel();
        if(!empty($AreaShow)){
            foreach($AreaShow as $k=>$v){
                $AreaShowLIst[$k]['area_id'] = $v;
                $AreaShowLIst[$k]['area_name'] = $Region->getOneByIdAndName($v,"region_name");
            }
        }else{
            $AreaShowLIst = array();
        }

        $CountArea = count($AreaShowLIst);

        //这边去查询一下交货地
//
//        $DeliveryShow = $search->getDeliveryShow("iq.area_id <> '' and iq.currency_id <> '' and iq.status = '2' ");
//        if(!empty($DeliveryShow)){
//            foreach($DeliveryShow as $key=>$var){
//                if(!empty($var['delivery_area'])){
//                    $delivery_areas[] =  Tools::substr($var['delivery_area'],0,2,"utf-8");
//                }
//                unset($DeliveryShow[$key]);
//            }
//        }
//        if(!empty($delivery_areas)){
//            $DeliveryShow = array_unique($delivery_areas);
//        }

        //这边去加载首页的数据
        if($orderby=='numdesc'){
            $order = "iq.num desc";
        }else if($orderby=='pricedesc'){
            $order = "min(iq.price) DESC";
        }else if($orderby=='priceasc'){
            $order = "min(iq.price) ASC";
        }else{
            $order = "iq.create_time desc";
        }

        $group = "iq.product_id";
        $totalItems =  $search->getPriceCountByWhere($wheres,$group,$having);
        $offset = 0;
        $page =  empty($page) ? 1 :$page;
        $offset = ($page - 1) * ITEM_PER_PAGE;
        if ($offset >= $totalItems) {
            $page = ceil ( $totalItems / ITEM_PER_PAGE );
            $offset = ($page - 1) * ITEM_PER_PAGE;
        }
        if ($offset < 0) {
            $offset = 0;
            $page = 1;
        }

        $data['list'] = $search->getPriceListByWhere($wheres,ITEM_PER_PAGE,$offset,$order,$group,$having);
        if(!empty($data['list'])){
            foreach($data['list'] as $key=>$var){
                $data['list'][$key]['price_num'] =count($search->getPriceBusinessByWhere("product_id = {$var['product_id']} and iq.status = '{$_suppliyStateCfg['up']}'"));
            }
        }

        $links = Pagination::createPage($url, ITEM_PER_PAGE, $page, $totalItems, 2 ,'_self',true);
        $linkpage = Tools::linkPage($url,  ITEM_PER_PAGE, $page, $totalItems, $target = '_self');
        $this->_view->kd = $kd;
        $this->_view->title = $this->_title;
        $this->_view->keywords  = $this->_keywords;
        $this->_view->description = $this->_description;
        $this->_view->_getAreaNames = $_getAreaNames;
        $this->_view->cate = $cate;
        $this->_view->data = $data['list'];
        $this->_view->CurrencyShow = $CurrencyShow;
        $this->_view->AreaShow = $AreaShowLIst;
//        $this->_view->DeliveryShow = $DeliveryShow;
        $this->_view->CountArea = $CountArea;
        $this->_view->links = $links;
        $this->_view->linkpage = $linkpage;

        $this->_view->page = $page;
        $this->_view->totalnum = $totalItems;
        $this->_view->cate_name = $cate_name;
        $this->_view->cates_name = $cates_name;
        $this->_view->currency_name = $currency_name;
        $this->_view->area_id = $area_id;
        $this->_view->area_name = $area_name;
        $this->_view->region_name = $region_name;
        $this->_view->brand_name = $brand_name;
        $this->_view->product_name = $product_name;
        $this->_view->order = $orderby;
        $this->_view->minprice = $minprice;
        $this->_view->maxprice = $maxprice;
        $this->_view->delivery_area  = $delivery_area ;
        $this->_view->list_search = $list_search;
    }


#########################################################################################
    public function pagejsonAction(){
        global $_suppliyStateCfg,$_sphinxConfig;
        define('ITEM_PER_PAGE', 10);
        $param = !empty($_GET['param']) ? $_GET['param']: '';
        $param['page'] = !empty($param['page'])? (int)$param['page'] :1;
        //参数转换
        //搜索配置
        $server = new SphinxClient();
        $server->SetServer($_sphinxConfig['host'],$_sphinxConfig['port']);
//        $server->SetMatchMode($_sphinxConfig['SPH_MATCH']);
        $server->SetArrayResult(true);
        $sphinx_offset = ($param['page']-1) *ITEM_PER_PAGE;
        //搜索状态为上架的
        $server->SetFilter("status",array($_suppliyStateCfg['up']));
        $server->SetLimits($sphinx_offset,ITEM_PER_PAGE,1000);
        $sphinx_info = $server->Query( $param['kd'],"quotation");
        //这上面的只去获取产品id product_id ，然后根据产品的id去查报价
        $conditions[] = "";

        if(!empty($param['cate_name'])){
            $conditions[] = "pc.cate_name like '%{$param['cate_name']}%'";
        }

        if(!empty($param['currency_name'])){
            $conditions[] = "rc.name like '%{$param['currency_name']}%'";
        }

        if(!empty($param['area_name'])){
            $conditions[] = "r.region_name like '%{$param['area_name']}%'";
        }

        $where= "1=1";
        if(empty($conditions[0]))
        {
            $where  = '1=1 ';
        } else {
            $where  .= " AND ".implode(' AND ', $conditions);
        }
        if(empty($sphinx_info['matches'])&&!empty($param['kd'])){
            $where .= " and iq.status= '{$_suppliyStateCfg['up']}' and iq.area_id <>'' and iq.currency_id <> '' and (p.product_name like '%{$param['kd']}%' or pc.cate_name like '%{$param['kd']}%' or pb.brand_name like '%{$param['kd']}%' or r.region_name like '%{$param['kd']}%' or iq.delivery_area like '%{$param['kd']}%')";
        }else{
            $where .= " and iq.status= '{$_suppliyStateCfg['up']}' and iq.area_id <>'' and iq.currency_id <> ''";
        }

        $search = new SearchModel();
        $order = "min(iq.price) ASC";
        $group = "iq.product_id";
        $totalItems =  $search->getPriceCountByWhere($where,$group);
        $offset = 0;
        $page =  empty($param['page']) ? 1 :$param['page'];
        $offset = ($page - 1) * ITEM_PER_PAGE;
        if ($offset >= $totalItems) {
            $page = ceil ( $totalItems / ITEM_PER_PAGE );
            $offset = ($page - 1) * ITEM_PER_PAGE;
        }
        if ($offset < 0) {
            $offset = 0;
            $page = 1;
        }

        $data['list'] = $search->getPriceListByWhere($offset,ITEM_PER_PAGE,$where,$order,$group);
        if(!empty($data['list'])){
            foreach($data['list'] as $key=>$var){
                $data['list'][$key]['price_num'] =count($search->getPriceBusinessByWhere("product_id = {$var['product_id']} and iq.status = '{$_suppliyStateCfg['up']}'"));
            }
        }

        if(!empty($data['list'])){
            foreach($data['list'] as $key=>$val){
                $data['list'][$key]['index_list'] = $search->getQuotationPriceListByWhere("product_id = {$val['product_id']} and iq.status = '{$_suppliyStateCfg['up']}'","iq.price ASC");
            }
        }

        //这边加载过滤地区的  index_list
        if(!empty($data['list'])){
            foreach($data['list'] as $key=>$row){
                if(!empty($row['index_list'])){
                    foreach($row['index_list'] as $kindex=>$klist){
                        $areas[] =  $klist['area_name'];
                    }
                }
            }
        }
        //这边去重,并去掉为空
        $areas = array_unique($areas);
        if(!empty($areas)){
            foreach($areas as $k=>$v){
                if(empty($v)){
                    unset($areas[$k]);
                }
            }
        }


        $data['kd'] = $param['kd'];
        $data['param'] = $param;
        $data['area'] = $areas;
        $data['sphinx'] = $sphinx_info;
        $data['total_num'] = $totalItems;
        $data['page_size'] = ITEM_PER_PAGE;
        $data['page_total_num'] = ceil ( $totalItems / ITEM_PER_PAGE );
        echo json_encode($data); die();
    }

    public function productjsonAction(){
       global $_suppliyStateCfg;
        $search = new SearchModel();
        $_GET['product_id'] = !empty($_GET['product_id']) ? (int)$_GET['product_id'] :0;

        if(empty($_GET['product_id'])){
            return null;
        }

        $index_list = $search->getQuotationPriceListByWhere("product_id = {$_GET['product_id']} and iq.status = '{$_suppliyStateCfg['up']}'","iq.price ASC");
        //这边对于自营的就没有公司和联系人

        echo json_encode($index_list); die();
    }

}